package com.atpy.reggie.controller;

import com.atpy.reggie.common.R;
import com.atpy.reggie.dto.UserDto;
import com.atpy.reggie.entity.Employee;
import com.atpy.reggie.entity.User;
import com.atpy.reggie.service.UserService;
import com.atpy.reggie.utils.ValidateCodeUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    //获取验证码
    @PostMapping("/sendMsg")
    public R<String> sendMsg(HttpSession session, @RequestBody User user) {
        //获取邮箱号
        //相当于发送短信定义的String to
        String email = user.getPhone();
        String subject = "啵啵外卖";
        //StringUtils.isNotEmpty字符串非空判断
        if (StringUtils.isNotEmpty(email)) {
            //发送一个四位数的验证码,把验证码变成String类型
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            String text = "【波波外卖】您好，您的登录验证码为：" + code + "，请尽快登录";
            log.info("验证码为：" + code);
            //发送短信
            userService.sendMsg(email,subject,text);
            //将验证码保存到session当中
            //将生成验证码缓存到redis中，并且设置有效期为5分钟
            redisTemplate.opsForValue().set(email,code,5, TimeUnit.MINUTES);
//            session.setAttribute(email, code);
            return R.success("验证码发送成功");
        }
        return R.error("验证码发送异常，请重新发送");
    }
    //登录
    @PostMapping("/login")
    //Map存JSON数据
    public R<User> login(HttpSession session, @RequestBody Map map) {
        //获取邮箱，用户输入的
        String phone = map.get("phone").toString();
        //获取验证码，用户输入的
        String code = map.get("code").toString();
        //获取session中保存的验证码
        //从redis中取出验证码
        Object sessionCode =redisTemplate.opsForValue().get(phone);
//        Object sessionCode = session.getAttribute(phone);
        //如果session的验证码和用户输入的验证码进行比对,&&同时
        if (sessionCode != null && sessionCode.equals(code)) {
            //要是User数据库没有这个邮箱则自动注册,先看看输入的邮箱是否存在数据库
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone, phone);
            //获得唯一的用户，因为手机号是唯一的
            User user = userService.getOne(queryWrapper);
            //要是User数据库没有这个邮箱则自动注册
            if (user == null) {
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                //取邮箱的前五位为用户名
                user.setName(phone.substring(0, 6));
                userService.save(user);
            }
            //不保存这个用户名就登不上去，因为过滤器需要得到这个user才能放行，程序才知道你登录了

            session.setAttribute("user", user.getId());
            redisTemplate.delete(phone);
            return R.success(user);
        }

        return R.error("登录失败");
    }

    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        request.getSession().removeAttribute("user");
        return R.success("退出成功");
    }
    @PostMapping("/register")
    public R<String> register(HttpServletRequest request,@RequestBody UserDto user) {

        log.info("------------------{}",user.toString());
        boolean b = userService.save(user);
        return R.success("注册成功");
    }

    //登录
    @PostMapping("/passwordlogin")
    //Map存JSON数据
    public R<User> passwordlogin(HttpSession session, @RequestBody Map map) {
        //获取邮箱，用户输入的
        String phone = map.get("phone").toString();
        //获取验证码，用户输入的
        String password = map.get("password").toString();
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone,phone);
        User user = userService.getOne(wrapper);
        if (user.getStatus() == 0){
            return R.error("账号被禁用");
        }
        if (user != null && user.getPassword().equals(password)) {
            //不保存这个用户名就登不上去，因为过滤器需要得到这个user才能放行，程序才知道你登录了
            session.setAttribute("user", user.getId());
            redisTemplate.delete(phone);
            return R.success(user);
        }

        return R.error("登录失败,邮箱或密码输入不正确");
    }


    // 查询用户个人信息接口
    @GetMapping("/{phone}")
    //Map存JSON数据
    public R<User> queryUserByPhone(@PathVariable("phone") String phone) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone,phone);
        User one = userService.getOne(wrapper);
        return R.success(one);
    }

    // 修改用户个人信息接口
    @PostMapping ("/updataUserById")
    //Map存JSON数据
    public R<String> updataUserByPhone(@RequestBody User user) {

        log.info(user.toString()+"+++++++++++++++++++++++++++++");
        boolean isupdate = userService.updateById(user);
        if (isupdate){
            return R.success("ok");
        }
        return R.error("修改失败");

    }

    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name){
        log.info("page={},pageSize={},name={}",page,pageSize,name);
        final val pageInfo = new Page(page, pageSize);
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.like(!org.springframework.util.StringUtils.isEmpty(name),User::getName,name);
        userService.page(pageInfo,queryWrapper);
        return R.success(pageInfo);
    }

    /*
    function queryUserById (id) {
  return $axios({
    url: `/user/${id}`,
    method: 'get'
  })
}
     */


    @GetMapping("/queryUserById/{id}")
    public R<User> queryUserById(@PathVariable("id") String id){

        log.info("Userid={}",id);
        Long value = Long.valueOf(id);
        User user = userService.getById(value);
        return R.success(user);
    }



    @PutMapping
    public R<String> update(@RequestBody User user,HttpServletRequest request){
        log.info("更改员工{}",user.toString());
//        Long empid = (Long) request.getSession().getAttribute("employee");
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setUpdateUser(empid);
        userService.updateById(user);
        return R.success("切换成功");
    }


}



